package com.skeyedu.consumer.controller;

import com.skeyedu.consumer.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/*
 * @author jChen
 * @date 2021/12/12 13:57
 * @detail:
 */
@RestController
@RequestMapping("/consumer")
public class ConsumerController {

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @RequestMapping("/{id}")
    public User findUserById(@PathVariable int id){
//        String url = "http://localhost:8080/user/"+id;
//        return restTemplate.getForObject(url,User.class);

        List<ServiceInstance> list = discoveryClient.getInstances("user-service");
        ServiceInstance instance = list.get(0);
        String host = instance.getHost();
        int port = instance.getPort();
        String url = "http://" + host+":"+port+"/user/"+id;
        System.out.println("得到的url:"+url);
        return restTemplate.getForObject(url,User.class);
    }
}
